package cc.fengz.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cc.fengz.utils.FileMd5;
import cc.fengz.utils.FileNameUtils;
import cc.fengz.utils.UrlUtils;
import cc.fengz.web.bean.FileInfo;
import cc.fengz.web.bean.FileMessage;
import cc.fengz.web.bean.ResultMessage;

import com.alibaba.fastjson.JSON;

public class Upload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String fileroot;
	private String filewebRoot;
	private String uploadPath = "eShop/upload/"; // 上传文件的目录
	private String tempPath = "eShop/uploadtmp/"; // 临时文件目录

	private int sizeMax = 3;// 图片最大上限
	private String[] fileType = new String[] { "jpg", "gif", "bmp", "png",
			".jpeg", ".ico" };

	public void destroy() {
		super.destroy();
	}

	public void init() throws ServletException {
		fileroot = this.getServletContext().getInitParameter("fileRoot");
		filewebRoot = this.getServletContext().getInitParameter("filewebRoot");
		uploadPath = fileroot + File.separator + "upload" + File.separator;
		tempPath = fileroot + File.separator + "uploadtmp" + File.separator;

		if (!new File(uploadPath).isDirectory()) {
			new File(uploadPath).mkdirs();
		}

		if (!new File(tempPath).isDirectory()) {
			new File(tempPath).mkdirs();
		}

	}

	/**
	 * 保存文件
	 * @param file
	 * @return
	 */
	private File saveFile(FileItem file) {
		String uuid = "";
		try {
			uuid = FileMd5.getMd5ByInputStream(file.getInputStream());
		} catch (Exception e) {
			uuid = UUID.randomUUID().toString();
		}

		String filename = uploadPath+ uuid + "." + FileNameUtils.getExtension(file.getName());
		
		filename = FileNameUtils.normalize(filename) ;

		File uploadFile = new File(filename);
		try {
			file.write(uploadFile) ;
		} catch (Exception e) {
			
			e.printStackTrace();
			return null ;
		}
		return uploadFile ;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		ResultMessage resultmsg =null;

		DiskFileItemFactory factory = new DiskFileItemFactory();

		factory.setSizeThreshold(5 * 1024); // 最大缓存
		factory.setRepository(new File(tempPath));// 临时文件目录

		ServletFileUpload upload = new ServletFileUpload(factory);

		upload.setSizeMax(sizeMax * 1024 * 1024);// 文件最大上限

		try {
			List<FileItem> items = upload.parseRequest(request);

			for (FileItem item : items) {
				// 获得文件名，这个文件名包括路径
				if (!item.isFormField() && item.getSize() > 0) {
					// 文件名
					String fileName = item.getName().toLowerCase();

					if (FileNameUtils.isExtension(fileName, fileType)) {

						File file = saveFile(item) ;
											
						if(null!=file){
							FileInfo info = new FileInfo() ; 
							FileMessage fileMessage = new FileMessage() ;
							
							
							info.setFilename(file.getName()) ;
							
							info.setSize(file.getTotalSpace()) ;
							info.setDownloadPath(UrlUtils.getRoot(request.getRequestURL())+filewebRoot+"upload/"+file.getName()) ;
							
							fileMessage.setFileinfo(info) ;
							
							
							resultmsg = fileMessage ;
							
							
							
						}
					} else {					
						resultmsg = new ResultMessage(false) ;
						resultmsg.setMsg("上传失败,请确认上传的文件存在并且类型是图片!") ;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			
			resultmsg = new ResultMessage(false) ;
			resultmsg.setMsg("上传失败,请确认上传的文件大小不能超过" + sizeMax
					+ "M") ;
		}
		
		PrintWriter pw = response.getWriter();
		
		pw.write(JSON.toJSONString(resultmsg)) ;
		
		pw.flush();
		pw.close();

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
